<?php
namespace app\admin\model;

use think\Model;
class Modules extends Model
{
    protected function initialize(){
        parent::initialize();
    }
    
    public function getModule($module_id)
    {
        $module = db('modules')->where('id',$module_id)->find();
        return $module;
    }
    
    
    public function addModules(array $data)
    {
        $modules = new Modules();
        $modules->module = $data['module'];
        $modules->created = time();
        $modules->save();
        $modules_id = $modules->id;
        if ($modules_id == false || empty($modules_id)){
            return false;
        }
        if (!is_array($data['submodule'])){
            return false;
        }
        $submodules = new Submodules();
        $list = [];
        foreach ($data['submodule'] as $k => $v){
            $list[$k]['submodule'] = $v['submodule'];
            $list[$k]['parent_id'] = $modules_id;
            $list[$k]['data_id'] = $v['data_id'];
            $list[$k]['url'] = $v['url'];
            $list[$k]['created'] = time();
        }
        $submodules->saveAll($list);
        return true;
    }
    
    public function saveSubmodules($submodulesArr,$module_id)
    {
        if (!is_array($submodulesArr)){
            return false;
        }
        $submodules = new Submodules();
        $list = array();
        foreach ($submodulesArr as $ak => $av){
            if (isset($av['id']) && !empty($av['id'])){
                $list[$ak]['id'] = $av['id'];
            }
            $list[$ak]['submodule'] = $av['submodule'];
            $list[$ak]['parent_id'] = $module_id;
            $list[$ak]['data_id'] = $av['data_id'];
            $list[$ak]['url'] = $av['url'];
            $list[$ak]['created'] = time();
        }
        $result = $submodules->saveAll($list);
        if ($result == false){
            return false;
        }
        return true;
    }
    
    
}